import store from '../store';

/**
 * @desc 函数防抖
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param immediate true 表立即执行，false 表非立即执行
 */
export function debounce(func, wait, immediate) {
  let timeout;

  return function(...args) {
    let context = this;
    if (timeout) clearTimeout(timeout);

    timeout = setTimeout(() => {
      timeout = null;
      if (!immediate) {
        func.apply(context, args);
      }
    }, wait);

    if (immediate) {
      func.apply(context, [...args]);
    }
  }
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 */
export function throttle(func, wait){
  let previous = 0;
  return function(...args) {
      let now = Date.now();
      let context = this;
      if (now - previous > wait) {
          func.apply(context, args);
          previous = now;
      } else {
        store.commit('showMessage', { message: `请勿频繁操作！请在${ wait / 1000 }秒后再操作！` , type: 'error' });
      }
  }
}